/**
 * Created by Administrator on 2017/9/17.
 */
const initialState = {
    list: [{item: 'test',done:false}],
    newToDo:''
};

const INPUT_CHANGE = 'my-app/toDoApp/INPUT_CHANGE';
const ADD_ITEM = 'my-app/toDoApp/ADD_ITEM';
const ITEM_CLICK = 'my-app/toDoApp/ITEM_CHANGE';
const DELETE_ITEM = 'my-app/toDoApp/DELETE_ITEM';

export function inputChange(event){
    return {
        type: INPUT_CHANGE,
        value: event.target.value
    }
}

export function addItem(event){
    event.preventDefault();

    return {
        type: ADD_ITEM
    }
}

export function itemChange(index){

    return {
        type: ITEM_CLICK,
        index: index
    }

}

export function deleteItem(index){

    return {
        type: DELETE_ITEM,
        index: index
    }
}

export default function reducer(state = initialState,action){
    // console.log("state,action",{state,action});
    switch(action.type){
        case INPUT_CHANGE:
            return Object.assign(
                {},
                state,
                {newToDo:action.value}
            );
        case ADD_ITEM:
            return Object.assign(
                {},
                state,
                {list:[...state.list, {item:state.newToDo,done:false}],newToDo:""}
            );
        case ITEM_CLICK:
            return Object.assign(
                {},
                state,
                {list: [
                    ...state.list.slice(0,action.index),
                    Object.assign({},state.list[action.index],{done: !state.list[action.index].done}),
                    ...state.list.slice(action.index+1)
                ]}
            );
        case DELETE_ITEM:
            return Object.assign(
            {},
            state,
            {list: [
                ...state.list.slice(0,action.index),
                ...state.list.slice(action.index+1)
            ]}
        );
        default:
            return state;
    }
}